{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "aa342f22",
      "metadata": {},
      "outputs": [],
      "source": [
        "print (\"Hello Pyhton\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "f7b4ec29",
      "metadata": {},
      "outputs": [],
      "source": [
        "a = 60 \n",
        "b = 13\n",
        "a & b\n",
        "a | b\n",
        "~ a\n",
        "a >> 2\n",
        "a << 2\n",
        "\n",
        "a and b \n",
        "a or b\n",
        "not a "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "67ee290f",
      "metadata": {},
      "outputs": [],
      "source": [
        "# while 带有else\n",
        "count = 0\n",
        "while count < 5:\n",
        "   print (count,\" is  less than 5\"), \n",
        "   count += 1\n",
        "else:\n",
        "   print (count, \" is not less than 5\"),"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "5ad91d34",
      "metadata": {},
      "outputs": [],
      "source": [
        "for letter in \"Python\":     # 第一个实例\n",
        "   print(\"当前字母 :\", letter)\n",
        "\n",
        "fruits = ['banana', 'apple',  'mango']\n",
        "\n",
        "for fruit in fruits:        # 第二个实例\n",
        "   print ('当前水果 :', fruit)\n",
        "print(\"Good bye!\")\n",
        "\n",
        "# 通过序列索引迭代\n",
        "fruits = ['banana', 'apple',  'mango']\n",
        "for index in range(len(fruits)):\n",
        "     print ('当前水果 :', fruits[index])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "49465caf",
      "metadata": {},
      "outputs": [],
      "source": [
        "for num in range(10,20):  # 迭代 10 到 20 之间的数字\n",
        "    for i in range(2,num): # 根据因子迭代\n",
        "      if num%i == 0:      # 确定第一个因子\n",
        "        j=num/i          # 计算第二个因子\n",
        "        print('%d 等于 %d * %d' % (num,i,j))\n",
        "        break            # 跳出当前循环\n",
        "    else:                  # 循环的 else 部分\n",
        "      print(num, '是一个质数')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "731bdb66",
      "metadata": {},
      "outputs": [],
      "source": [
        "# 循环嵌套\n",
        "\n",
        "for letter in 'Python':     # First Example\n",
        "    if letter == 'h':\n",
        "      break\n",
        "    print('Current Letter :', letter)  \n",
        "    var = 10                    # Second Example\n",
        "    while var > 0:              \n",
        "        print ('Current variable value :', var)\n",
        "        var = var -1\n",
        "        if var == 5:\n",
        "            break\n",
        "print (\"Good bye!\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "add35458",
      "metadata": {},
      "outputs": [],
      "source": [
        "# contiue\n",
        "\n",
        "for letter in 'Python':     # 第一个实例\n",
        "   if letter == 'h':\n",
        "      continue\n",
        "   print ('当前字母 :', letter)                    # 第二个实例   \n",
        "   var = 10  \n",
        "   while var > 0:         \n",
        "    var = var -1\n",
        "    if var == 5:\n",
        "      continue\n",
        "    print ('当前变量值 :', var)\n",
        "print (\"Good bye!\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "783ce42f",
      "metadata": {},
      "outputs": [],
      "source": [
        "# 乘法口诀\n",
        "for a in range(1,10):\n",
        "    for b in range(1,a+1):\n",
        "        print(b,'*',a, '=', a * b,end=' ')\n",
        "    print()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "72555f0b",
      "metadata": {},
      "outputs": [],
      "source": [
        "for letter in 'Python':\n",
        "   if letter == 'h':\n",
        "        pass\n",
        "        print('这是 pass 块')\n",
        "   print('当前字母 :', letter)\n",
        "print(\"Good bye!\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1e1796f6",
      "metadata": {},
      "source": [
        "python Number、字符串、列表、元组、字典 知识点较多，实战中掌握"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "ac363643",
      "metadata": {},
      "outputs": [],
      "source": [
        "#!/usr/bin/env python3\n",
        "# Python3 字符串、列表、元组、字典用法示例\n",
        "\n",
        "def string_demo():\n",
        "    \"\"\"字符串（str）用法示例\"\"\"\n",
        "    print(\"===== 字符串操作 =====\")\n",
        "    # 1. 创建字符串\n",
        "    s1 = \"Hello\"\n",
        "    s2 = 'World'\n",
        "    s3 = \"\"\"多行\n",
        "字符串\"\"\"\n",
        "    s4 = r\"C:\\path\\no\\escape\"  # 原始字符串（不转义）\n",
        "\n",
        "    # 2. 字符串拼接与重复\n",
        "    print(\"拼接:\", s1 + \" \" + s2)  # Hello World\n",
        "    print(\"重复:\", s1 * 2)         # HelloHello\n",
        "\n",
        "    # 3. 索引与切片\n",
        "    s = \"Python\"\n",
        "    print(\"索引[0]:\", s[0])       # P\n",
        "    print(\"索引[-1]:\", s[-1])     # n\n",
        "    print(\"切片[1:4]:\", s[1:4])   # yth\n",
        "    print(\"反转切片[::-1]:\", s[::-1])  # nohtyP\n",
        "\n",
        "    # 4. 常用方法\n",
        "    print(\"大写:\", s1.upper())        # HELLO\n",
        "    print(\"小写:\", s2.lower())        # world\n",
        "    print(\"替换:\", s1.replace(\"H\", \"J\"))  # Jello\n",
        "    print(\"分割:\", \"a,b,c\".split(\",\"))  # ['a', 'b', 'c']\n",
        "    print(\"连接:\", \"-\".join([\"a\", \"b\", \"c\"]))  # a-b-c\n",
        "    print(\"是否以He开头:\", s1.startswith(\"He\"))  # True\n",
        "    print(\"去除空格:\", \"  test  \".strip())  # test\n",
        "    print(\"格式化:\", \"Name: {0}, Age: {1}\".format(\"Alice\", 30))  # Name: Alice, Age: 30\n",
        "    print(\"f-string格式化:\", f\"Name: {'Bob'}, Age: {25}\")  # Name: Bob, Age: 25\n",
        "    print()\n",
        "\n",
        "\n",
        "def list_demo():\n",
        "    \"\"\"列表（list）用法示例\"\"\"\n",
        "    print(\"===== 列表操作 =====\")\n",
        "    # 1. 创建列表\n",
        "    lst = [1, 2, 3, \"a\", \"b\"]\n",
        "    empty_lst = []\n",
        "    range_lst = list(range(5))  # [0, 1, 2, 3, 4]\n",
        "\n",
        "    # 2. 访问元素\n",
        "    print(\"列表:\", lst)\n",
        "    print(\"索引[2]:\", lst[2])    # 3\n",
        "    print(\"切片[1:4]:\", lst[1:4])  # [2, 3, 'a']\n",
        "\n",
        "    # 3. 修改元素\n",
        "    lst[0] = 100\n",
        "    print(\"修改后:\", lst)  # [100, 2, 3, 'a', 'b']\n",
        "\n",
        "    # 4. 常用方法\n",
        "    lst.append(4)  # 末尾添加\n",
        "    print(\"append后:\", lst)  # [100, 2, 3, 'a', 'b', 4]\n",
        "    \n",
        "    lst.insert(2, \"inserted\")  # 指定位置插入\n",
        "    print(\"insert后:\", lst)  # [100, 2, 'inserted', 3, 'a', 'b', 4]\n",
        "    \n",
        "    popped = lst.pop()  # 移除末尾元素\n",
        "    print(\"pop返回值:\", popped, \" pop后:\", lst)  # 4 [100, 2, 'inserted', 3, 'a', 'b']\n",
        "    \n",
        "    lst.remove(\"a\")  # 移除指定值\n",
        "    print(\"remove后:\", lst)  # [100, 2, 'inserted', 3, 'b']\n",
        "    \n",
        "    lst.reverse()  # 反转\n",
        "    print(\"reverse后:\", lst)  # ['b', 3, 'inserted', 2, 100]\n",
        "    \n",
        "    num_lst = [3, 1, 4, 1, 5]\n",
        "    num_lst.sort()  # 排序（原地修改）\n",
        "    print(\"排序后:\", num_lst)  # [1, 1, 3, 4, 5]\n",
        "    \n",
        "    print(\"列表长度:\", len(lst))  # 5\n",
        "    print(\"是否包含3:\", 3 in lst)  # True\n",
        "    print()\n",
        "\n",
        "\n",
        "def tuple_demo():\n",
        "    \"\"\"元组（tuple）用法示例\"\"\"\n",
        "    print(\"===== 元组操作 =====\")\n",
        "    # 1. 创建元组（不可变序列）\n",
        "    tpl = (1, 2, 3, \"a\")\n",
        "    single_tpl = (5,)  # 单个元素必须加逗号\n",
        "    empty_tpl = ()\n",
        "    tpl_from_list = tuple([1, 2, 3])  # 从列表转换\n",
        "\n",
        "    # 2. 访问元素（与列表类似）\n",
        "    print(\"元组:\", tpl)\n",
        "    print(\"索引[1]:\", tpl[1])  # 2\n",
        "    print(\"切片[:3]:\", tpl[:3])  # (1, 2, 3)\n",
        "\n",
        "    # 3. 元组不可修改（会报错）\n",
        "    # tpl[0] = 100  # TypeError: 'tuple' object does not support item assignment\n",
        "\n",
        "    # 4. 常用操作\n",
        "    print(\"元组拼接:\", tpl + (4, 5))  # (1, 2, 3, 'a', 4, 5)\n",
        "    print(\"元组重复:\", (1, 2) * 3)    # (1, 2, 1, 2, 1, 2)\n",
        "    print(\"元素个数:\", len(tpl))      # 4\n",
        "    print(\"元素索引:\", tpl.index(\"a\"))  # 3\n",
        "    print(\"元素出现次数:\", (1, 2, 2, 3).count(2))  # 2\n",
        "    \n",
        "    # 元组拆包\n",
        "    a, b, c = (10, 20, 30)\n",
        "    print(\"拆包结果:\", a, b, c)  # 10 20 30\n",
        "    print()\n",
        "\n",
        "\n",
        "def dict_demo():\n",
        "    \"\"\"字典（dict）用法示例\"\"\"\n",
        "    print(\"===== 字典操作 =====\")\n",
        "    # 1. 创建字典（键值对集合）\n",
        "    dic = {\"name\": \"Alice\", \"age\": 30, \"city\": \"New York\"}\n",
        "    empty_dic = {}\n",
        "    dic_from_tuples = dict([(\"name\", \"Bob\"), (\"age\", 25)])  # 从元组列表创建\n",
        "\n",
        "    # 2. 访问元素\n",
        "    print(\"字典:\", dic)\n",
        "    print(\"获取name:\", dic[\"name\"])  # Alice\n",
        "    print(\"get方法获取age:\", dic.get(\"age\"))  # 30\n",
        "    print(\"get方法获取不存在的键:\", dic.get(\"gender\", \"unknown\"))  # unknown\n",
        "\n",
        "    # 3. 修改元素\n",
        "    dic[\"age\"] = 31  # 修改已有键\n",
        "    dic[\"gender\"] = \"female\"  # 添加新键值对\n",
        "    print(\"修改后:\", dic)  # {'name': 'Alice', 'age': 31, 'city': 'New York', 'gender': 'female'}\n",
        "\n",
        "    # 4. 常用方法\n",
        "    print(\"所有键:\", dic.keys())  # dict_keys(['name', 'age', 'city', 'gender'])\n",
        "    print(\"所有值:\", dic.values())  # dict_values(['Alice', 31, 'New York', 'female'])\n",
        "    print(\"所有键值对:\", dic.items())  # dict_items([('name', 'Alice'), ...])\n",
        "    \n",
        "    popped_value = dic.pop(\"city\")  # 移除指定键\n",
        "    print(\"pop返回值:\", popped_value, \" pop后:\", dic)  # New York {'name': 'Alice', 'age': 31, 'gender': 'female'}\n",
        "    \n",
        "    # 遍历字典\n",
        "    print(\"遍历键值对:\")\n",
        "    for key, value in dic.items():\n",
        "        print(f\"{key}: {value}\")\n",
        "    \n",
        "    # 字典推导式\n",
        "    squared = {x: x**2 for x in range(5)}\n",
        "    print(\"字典推导式:\", squared)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}\n",
        "    print()\n",
        "\n",
        "\n",
        "def main():\n",
        "    string_demo()\n",
        "    list_demo()\n",
        "    tuple_demo()\n",
        "    dict_demo()\n",
        "\n",
        "if __name__ == \"__main__\":\n",
        "    main()\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "2c7baf5d",
      "metadata": {},
      "outputs": [],
      "source": [
        "import time,calendar\n",
        "# struct_time 时间元组\n",
        "localtime = time.localtime(time.time())\n",
        "print('当前时间:',localtime)\n",
        "ztime = time.asctime(time.localtime(time.time()))\n",
        "print('格式化时间',ztime)\n",
        "print(time.strftime('%a %b %d %H:%M:%S %Y',time.localtime()))\n",
        "# 2016年 1月 日历\n",
        "print(calendar.month(2016,1))\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "dbd800b7",
      "metadata": {},
      "outputs": [],
      "source": [
        "# 函数\n",
        "def printme( str ):\n",
        "   \"打印传入的字符串到标准显示设备上\"\n",
        "   print (str)   \n",
        "   return\n",
        "\n",
        "printme(\"我要调用用户自定义函数!\")\n",
        "printme(\"再次调用同一函数\");\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "48ef8a83",
      "metadata": {},
      "source": [
        "在 python 中，类型属于对象，变量是没有类型的：\n",
        "在 python 中，strings, tuples, 和 numbers 是不可更改的对象，而 list,dict 等则是可以修改的对象。\n",
        "- 不可变类型：变量赋值 a=5 后再赋值 a=10，这里实际是新生成一个 int 值对象 10，再让 a 指向它，而 5 被丢弃，不是改变a的值，相当于新生成了a。\n",
        "- 可变类型：变量赋值 la=[1,2,3,4] 后再赋值 la[2]=5 则是将 list la 的第三个元素值更改，本身la没有动，只是其内部的一部分值被修改了。\n",
        "\n",
        "python 中一切都是对象，严格意义我们不能说值传递还是引用传递，我们应该说传不可变对象和传可变对象。\n",
        "- 不可变类型：类似 c++ 的值传递，如 整数、字符串、元组。如fun（a），传递的只是a的值，没有影响a对象本身。比如在 fun（a）内部修改 a 的值，只是修改另一个复制的对象，不会影响 a 本身。\n",
        "- 可变类型：类似 c++ 的引用传递，如 列表，字典。如 fun（la），则是将 la 真正的传过去，修改后fun外部的la也会受影响"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "c6963f0f",
      "metadata": {},
      "outputs": [],
      "source": [
        "# lambda 函数\n",
        " # 可写函数说明\n",
        "sum = lambda arg1, arg2: arg1 + arg2;\n",
        " # 调用sum函数print \"相加后的值为 : \", \n",
        "print(\"相加后的值为 : \", sum( 20, 20 ))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "c0388e22",
      "metadata": {},
      "outputs": [],
      "source": [
        "# 全局变量、局部变量\n",
        "total = 0; # 这是一个全局变量# 可写函数说明\n",
        "def sum( arg1, arg2 ):\n",
        "   #返回2个参数的和.\"\n",
        "    total = arg1 + arg2; # total在这里是局部变量.\n",
        "    print(\"函数内是局部变量 : \", total)\n",
        "    return total;\n",
        " #调用sum函数\n",
        "sum( 10, 20 );\n",
        "print(\"函数外是全局变量 : \", total)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "5d62a2ce",
      "metadata": {},
      "source": [
        "变量是拥有匹配对象的名字（标识符）。\n",
        "命名空间是一个包含了变量名称们（键）和它们各自相应的对象们（值）的字典。\n",
        "一个 Python 表达式可以访问局部命名空间和全局命名空间里的变量。如果一个局部变量和一个全局变量重名，则局部变量会覆盖全局变量。\n",
        "Python 会智能地猜测一个变量是局部的还是全局的，它假设任何在函数内赋值的变量都是局部的。\n",
        "\n",
        "因此，如果要给全局变量在一个函数里赋值，必须使用 global 语句。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "ef68fb62",
      "metadata": {},
      "outputs": [],
      "source": [
        "# 全局变量 示例\n",
        "Money = 2000\n",
        "def AddMoney():\n",
        "   # 想改正代码就取消以下注释:\n",
        "   global Money\n",
        "   Money = Money + 1\n",
        "print(Money)\n",
        "AddMoney()\n",
        "print(Money)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "2aa8db5b",
      "metadata": {},
      "outputs": [],
      "source": [
        "# 文件IO\n",
        "\n",
        "# 键盘输入 python3 input  整合python raw_input 和 input\n",
        "str = input(\"请输入：\")\n",
        "# 需要转换\n",
        "str = int(str)\n",
        "print(\"你输入的内容是: \", str+456)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "5eb2155b",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Python3 文件写入示例\n",
        "\n",
        "# 1. 基本写入（覆盖模式）\n",
        "try:\n",
        "    # 使用with语句自动管理文件关闭\n",
        "    with open('example.txt', 'w', encoding='utf-8') as f:\n",
        "        # 写入单行文本\n",
        "        f.write(\"Hello, World!\\n\")\n",
        "        \n",
        "        # 写入多行文本\n",
        "        lines = [\"这是第一行\\n\", \"这是第二行\\n\", \"这是第三行\\n\"]\n",
        "        f.writelines(lines)\n",
        "        \n",
        "    print(\"基本写入完成\")\n",
        "\n",
        "except IOError as e:\n",
        "    print(f\"写入错误: {e}\")\n",
        "\n",
        "# 2. 追加写入（不覆盖原有内容）\n",
        "try:\n",
        "    with open('example.txt', 'a', encoding='utf-8') as f:\n",
        "        f.write(\"这是追加的内容\\n\")\n",
        "        f.write(\"这是第二行追加的内容\\n\")\n",
        "    \n",
        "    print(\"追加写入完成\")\n",
        "\n",
        "except IOError as e:\n",
        "    print(f\"追加错误: {e}\")\n",
        "\n",
        "# 3. 二进制文件写入示例（复制图片）\n",
        "def copy_binary_file(src_path, dst_path):\n",
        "    try:\n",
        "        with open(src_path, 'rb') as src, open(dst_path, 'wb') as dst:\n",
        "            # 读取并写入二进制数据\n",
        "            dst.write(src.read())\n",
        "        print(f\"二进制文件已从 {src_path} 复制到 {dst_path}\")\n",
        "    except FileNotFoundError:\n",
        "        print(f\"错误: 源文件 {src_path} 不存在\")\n",
        "    except IOError as e:\n",
        "        print(f\"二进制文件操作错误: {e}\")\n",
        "\n",
        "# 调用示例（请确保当前目录有source.jpg文件）\n",
        "# copy_binary_file('source.jpg', 'copied.jpg')\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b349dc38",
      "metadata": {},
      "outputs": [],
      "source": [
        "import os\n",
        "import shutil\n",
        "from pathlib import Path\n",
        "# 文件目录\n",
        "def file_operations_demo():\n",
        "    # 创建测试文件\n",
        "    with open(\"test.txt\", \"w\") as f:\n",
        "        f.write(\"测试文件\")\n",
        "    \n",
        "    # 创建单级目录\n",
        "    os.mkdir(\"test_dir\")\n",
        "    print(\"创建单级目录: test_dir\")\n",
        "    \n",
        "    # 创建多级目录\n",
        "    Path(\"parent/child/grandchild\").mkdir(parents=True, exist_ok=True)\n",
        "    print(\"创建多级目录: parent/child/grandchild\")\n",
        "    \n",
        "    # 重命名文件\n",
        "    os.rename(\"test.txt\", \"renamed_test.txt\")\n",
        "    print(\"文件重命名: test.txt -> renamed_test.txt\")\n",
        "    \n",
        "    # 重命名目录\n",
        "    Path(\"test_dir\").rename(\"renamed_dir\")\n",
        "    print(\"目录重命名: test_dir -> renamed_dir\")\n",
        "    \n",
        "    # 删除文件\n",
        "    os.remove(\"renamed_test.txt\")\n",
        "    print(\"删除文件: renamed_test.txt\")\n",
        "    \n",
        "    # 删除空目录\n",
        "    Path(\"renamed_dir\").rmdir()\n",
        "    print(\"删除空目录: renamed_dir\")\n",
        "    \n",
        "    # 删除多级目录（非空）\n",
        "    # 先在目录中创建一个文件\n",
        "    with open(\"parent/child/grandchild/file.txt\", \"w\") as f:\n",
        "        f.write(\"测试\")\n",
        "    # 删除整个目录树\n",
        "    shutil.rmtree(\"parent\")\n",
        "    print(\"删除多级目录: parent（包含子目录和文件）\")\n",
        "\n",
        "if __name__ == \"__main__\":\n",
        "    file_operations_demo()\n",
        "    print(\"所有操作完成\")\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "7ce853b8",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Python3 异常处理综合示例\n",
        "\n",
        "# 1. 定义自定义异常\n",
        "class NegativeNumberError(Exception):\n",
        "    \"\"\"自定义异常：处理负数输入的情况\"\"\"\n",
        "    def __init__(self, number, message=\"不允许使用负数\"):\n",
        "        self.number = number\n",
        "        self.message = message\n",
        "        super().__init__(self.message)\n",
        "\n",
        "    def __str__(self):\n",
        "        return f\"{self.number} 是负数 -> {self.message}\"\n",
        "\n",
        "\n",
        "class TooLargeNumberError(Exception):\n",
        "    \"\"\"自定义异常：处理数值过大的情况\"\"\"\n",
        "    pass\n",
        "\n",
        "\n",
        "def process_number(num):\n",
        "    \"\"\"处理数字的函数，包含多种异常场景\"\"\"\n",
        "    # 主动抛出异常\n",
        "    if num < 0:\n",
        "        # 抛出自定义异常\n",
        "        raise NegativeNumberError(num)\n",
        "    if num > 1000:\n",
        "        # 抛出带有自定义消息的异常\n",
        "        raise TooLargeNumberError(f\"数值 {num} 太大，不能超过 1000\")\n",
        "    \n",
        "    # 可能触发内置异常的操作\n",
        "    result = 100 / num  # 可能触发 ZeroDivisionError\n",
        "    return result\n",
        "\n",
        "\n",
        "def exception_demo():\n",
        "    # 测试数据列表\n",
        "    test_numbers = [10, 0, -5, 2000, \"not a number\"]\n",
        "    \n",
        "    for num in test_numbers:\n",
        "        print(f\"\\n----- 测试数值: {num} -----\")\n",
        "        \n",
        "        try:\n",
        "            # 尝试执行可能出错的代码\n",
        "            print(f\"开始处理 {num}\")\n",
        "            result = process_number(num)\n",
        "        except ZeroDivisionError:\n",
        "            # 捕获特定异常\n",
        "            print(\"错误：除数不能为零！\")\n",
        "        except NegativeNumberError as e:\n",
        "            # 捕获自定义异常并访问其属性\n",
        "            print(f\"捕获到自定义异常: {e}\")\n",
        "            print(f\"异常中的数值: {e.number}\")\n",
        "        except TooLargeNumberError as e:\n",
        "            print(f\"捕获到自定义异常: {e}\")\n",
        "        except TypeError:\n",
        "            # 捕获类型错误\n",
        "            print(f\"错误：数据类型不正确，需要数字类型，实际是 {type(num)}\")\n",
        "        except Exception as e:\n",
        "            # 捕获所有其他未预料到的异常（不推荐在生产环境中这样做）\n",
        "            print(f\"发生了未预料到的错误: {e}\")\n",
        "            print(f\"错误类型: {type(e).__name__}\")\n",
        "        else:\n",
        "            # 如果没有发生异常，执行此块\n",
        "            print(f\"处理成功！结果: {result}\")\n",
        "        finally:\n",
        "            # 无论是否发生异常，都会执行此块\n",
        "            print(\"当前数值的处理流程结束\")\n",
        "    \n",
        "    # 演示嵌套异常处理\n",
        "    print(\"\\n----- 测试嵌套异常处理 -----\")\n",
        "    try:\n",
        "        try:\n",
        "            print(\"内部 try 块执行\")\n",
        "            raise ValueError(\"这是一个值错误\")\n",
        "        except TypeError:\n",
        "            print(\"内部 except 块捕获到类型错误\")\n",
        "        finally:\n",
        "            print(\"内部 finally 块执行\")\n",
        "    except ValueError as e:\n",
        "        print(f\"外部 except 块捕获到值错误: {e}\")\n",
        "    finally:\n",
        "        print(\"外部 finally 块执行\")\n",
        "\n",
        "\n",
        "if __name__ == \"__main__\":\n",
        "    exception_demo()\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b2eb7e04",
      "metadata": {},
      "source": [
        "单下划线、双下划线、头尾双下划线说明：\n",
        " - __foo__: 定义的是特列方法，类似 __init__() 之类的。\n",
        "\n",
        " - _foo: 以单下划线开头的表示的是 protected 类型的变量，即保护类型只能允许其本身与子类进行访问，不能用于 from module import *\n",
        "\n",
        " - __foo: 双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "134b2dcc",
      "metadata": {},
      "outputs": [],
      "source": [
        "#演示Python3中对象的基本用法\n",
        "\n",
        "# 1. 定义一个基础类（父类）\n",
        "class Person:\n",
        "    # 类属性（所有实例共享）\n",
        "    species = \"人类\"\n",
        "    \n",
        "    # 构造方法：初始化对象属性\n",
        "    def __init__(self, name, age):\n",
        "        # 实例属性\n",
        "        self.name = name  # 公开属性\n",
        "        self._age = age   # 单下划线表示受保护属性（约定）\n",
        "    \n",
        "    # 实例方法\n",
        "    def introduce(self):\n",
        "        \"\"\"自我介绍的方法\"\"\"\n",
        "        return f\"大家好，我叫{self.name}，今年{self._age}岁。\"\n",
        "    \n",
        "    # 访问器方法（获取属性）\n",
        "    def get_age(self):\n",
        "        return self._age\n",
        "    \n",
        "    # 修改器方法（修改属性）\n",
        "    def set_age(self, new_age):\n",
        "        if new_age > 0 and new_age < 150:\n",
        "            self._age = new_age\n",
        "        else:\n",
        "            raise ValueError(\"年龄必须在1-149之间\")\n",
        "    \n",
        "    # 类方法（用@classmethod装饰）\n",
        "    @classmethod\n",
        "    def get_species(cls):\n",
        "        return f\"物种: {cls.species}\"\n",
        "    \n",
        "    # 静态方法（用@staticmethod装饰）\n",
        "    @staticmethod\n",
        "    def is_adult(age):\n",
        "        \"\"\"判断是否成年\"\"\"\n",
        "        return age >= 18\n",
        "\n",
        "\n",
        "# 2. 定义一个继承类（子类）\n",
        "class Student(Person):\n",
        "    # 子类构造方法\n",
        "    def __init__(self, name, age, school, grade):\n",
        "        # 调用父类构造方法\n",
        "        super().__init__(name, age)\n",
        "        self.school = school\n",
        "        self.grade = grade\n",
        "    \n",
        "    # 重写父类方法\n",
        "    def introduce(self):\n",
        "        base_info = super().introduce()  # 调用父类方法\n",
        "        return f\"{base_info} 我在{self.school}上{self.grade}年级。\"\n",
        "    \n",
        "    # 子类特有方法\n",
        "    def study(self, subject):\n",
        "        return f\"{self.name}正在学习{subject}。\"\n",
        "\n",
        "\n",
        "# 3. 对象的使用示例\n",
        "def object_demo():\n",
        "    # 创建Person类的实例（对象）\n",
        "    person1 = Person(\"张三\", 25)\n",
        "    print(\"===== Person对象示例 =====\")\n",
        "    # 访问对象属性\n",
        "    print(f\"姓名: {person1.name}\")\n",
        "    # 调用对象方法\n",
        "    print(person1.introduce())\n",
        "    # 使用访问器方法\n",
        "    print(f\"年龄: {person1.get_age()}\")\n",
        "    \n",
        "    # 修改属性\n",
        "    person1.set_age(26)\n",
        "    print(f\"修改后的年龄: {person1.get_age()}\")\n",
        "    \n",
        "    # 调用类方法\n",
        "    print(Person.get_species())\n",
        "    # 调用静态方法\n",
        "    print(f\"是否成年: {Person.is_adult(person1.get_age())}\")\n",
        "    \n",
        "    # 创建Student子类的实例\n",
        "    student1 = Student(\"李四\", 16, \"阳光中学\", \"高一\")\n",
        "    print(\"\\n===== Student对象示例 =====\")\n",
        "    # 调用重写后的方法\n",
        "    print(student1.introduce())\n",
        "    # 调用子类特有方法\n",
        "    print(student1.study(\"数学\"))\n",
        "    # 访问继承的属性\n",
        "    print(f\"学生年龄: {student1.get_age()}\")\n",
        "    # 调用继承的静态方法\n",
        "    print(f\"学生是否成年: {Student.is_adult(student1.get_age())}\")\n",
        "    \n",
        "    # 检查对象类型\n",
        "    print(f\"\\nstudent1是否为Person类型: {isinstance(student1, Person)}\")\n",
        "    print(f\"person1是否为Student类型: {isinstance(person1, Student)}\")\n",
        "\n",
        "\n",
        "if __name__ == \"__main__\":\n",
        "    object_demo()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "31899caa",
      "metadata": {},
      "outputs": [],
      "source": [
        "import re\n",
        "\n",
        "def regex_demo():\n",
        "    # 1. 基础匹配：验证手机号（11位数字，以1开头）\n",
        "    phone_pattern = r'^1\\d{10}$'\n",
        "    phones = [\"13812345678\", \"1234567890\", \"189abc12345\"]\n",
        "    for phone in phones:\n",
        "        if re.match(phone_pattern, phone):\n",
        "            print(f\"{phone} 是合法手机号\")\n",
        "        else:\n",
        "            print(f\"{phone} 是非法手机号\")\n",
        "\n",
        "    # 2. 查找所有匹配：提取文本中的邮箱\n",
        "    text = \"联系我们：support@example.com 或 sales+info@company.cn\"\n",
        "    email_pattern = r'\\w+[+\\w]*@\\w+\\.\\w+'  # 简单邮箱正则\n",
        "    emails = re.findall(email_pattern, text)\n",
        "    print(\"\\n提取到的邮箱：\", emails)\n",
        "\n",
        "    # 3. 替换匹配内容：打码手机号中间4位\n",
        "    def mask_phone(match):\n",
        "        phone = match.group()  # 获取匹配的完整字符串\n",
        "        return phone[:3] + '****' + phone[7:]\n",
        "\n",
        "    text = \"我的手机号是13812345678，你的是13987654321\"\n",
        "    masked_text = re.sub(r'1\\d{10}', mask_phone, text)\n",
        "    print(\"\\n打码后的文本：\", masked_text)\n",
        "\n",
        "    # 4. 分割字符串：按任意空白字符分割\n",
        "    text = \"hello   world\\tpython\\nregex\"\n",
        "    parts = re.split(r'\\s+', text)  # \\s+ 匹配一个或多个空白字符\n",
        "    print(\"\\n分割结果：\", parts)\n",
        "\n",
        "    # 5. 分组提取：从URL中提取域名和路径\n",
        "    url = \"https://www.example.com/path/to/page?query=1\"\n",
        "    url_pattern = r'https?://([\\w.]+)/(.+)\\?'\n",
        "    match = re.search(url_pattern, url)\n",
        "    if match:\n",
        "        domain = match.group(1)  # 第1个分组（域名）\n",
        "        path = match.group(2)    # 第2个分组（路径）\n",
        "        print(f\"\\n域名：{domain}，路径：{path}\")\n",
        "\n",
        "    # 6. 修饰符示例：忽略大小写匹配\n",
        "    text = \"Hello HELLO hello\"\n",
        "    pattern = r'hello'\n",
        "    # 不忽略大小写\n",
        "    print(\"\\n不忽略大小写：\", re.findall(pattern, text))\n",
        "    # 忽略大小写（re.I 修饰符）\n",
        "    print(\"忽略大小写：\", re.findall(pattern, text, re.I))\n",
        "\n",
        "if __name__ == \"__main__\":\n",
        "    regex_demo()\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3a2a2d43",
      "metadata": {},
      "source": [
        "Python 操作Mysql 见 mysqlPy.py 文件"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "9912b053",
      "metadata": {},
      "source": [
        "Python 网络编程、SMTP发送邮件"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "c4a608e0",
      "metadata": {},
      "outputs": [],
      "source": [
        "import threading\n",
        "import time\n",
        "import random\n",
        "from concurrent.futures import ThreadPoolExecutor\n",
        "\n",
        "# 全局变量（多线程共享）\n",
        "counter = 0\n",
        "# 互斥锁（解决资源竞争）\n",
        "lock = threading.Lock()\n",
        "\n",
        "def basic_thread_demo():\n",
        "    \"\"\"基础线程创建示例：通过函数和继承创建线程\"\"\"\n",
        "    # 1. 通过目标函数创建线程\n",
        "    def print_numbers(name, delay):\n",
        "        for i in range(5):\n",
        "            time.sleep(delay)\n",
        "            print(f\"线程 {name}: {i}\")\n",
        "\n",
        "    # 创建线程\n",
        "    t1 = threading.Thread(target=print_numbers, args=(\"T1\", 0.5))\n",
        "    t2 = threading.Thread(target=print_numbers, args=(\"T2\", 0.8))\n",
        "\n",
        "    # 启动线程\n",
        "    t1.start()\n",
        "    t2.start()\n",
        "\n",
        "    # 等待线程结束\n",
        "    t1.join()\n",
        "    t2.join()\n",
        "    print(\"基础线程示例结束\\n\")\n",
        "\n",
        "# 2. 通过继承 Thread 类创建线程\n",
        "class CustomThread(threading.Thread):\n",
        "    def __init__(self, name, delay):\n",
        "        super().__init__()\n",
        "        self.name = name\n",
        "        self.delay = delay\n",
        "\n",
        "    def run(self):  # 线程启动后执行的方法\n",
        "        for i in range(3):\n",
        "            time.sleep(self.delay)\n",
        "            print(f\"自定义线程 {self.name}: {i}\")\n",
        "\n",
        "def custom_thread_demo():\n",
        "    t1 = CustomThread(\"CT1\", 0.3)\n",
        "    t2 = CustomThread(\"CT2\", 0.6)\n",
        "    t1.start()\n",
        "    t2.start()\n",
        "    t1.join()\n",
        "    t2.join()\n",
        "    print(\"自定义线程示例结束\\n\")\n",
        "\n",
        "def thread_synchronization_demo():\n",
        "    \"\"\"线程同步示例：使用锁解决资源竞争\"\"\"\n",
        "    def increment_counter(name):\n",
        "        global counter\n",
        "        for _ in range(100000):\n",
        "            # 获取锁（确保同一时间只有一个线程执行临界区）\n",
        "            with lock:  # 自动释放锁，替代 lock.acquire() 和 lock.release()\n",
        "                counter += 1\n",
        "            # 模拟其他操作（无需锁）\n",
        "            time.sleep(0.0001)\n",
        "        print(f\"线程 {name} 完成，当前计数器: {counter}\")\n",
        "\n",
        "    # 创建多个线程操作共享变量\n",
        "    threads = [\n",
        "        threading.Thread(target=increment_counter, args=(f\"T{i}\",))\n",
        "        for i in range(5)\n",
        "    ]\n",
        "\n",
        "    # 启动所有线程\n",
        "    start_time = time.time()\n",
        "    for t in threads:\n",
        "        t.start()\n",
        "\n",
        "    # 等待所有线程结束\n",
        "    for t in threads:\n",
        "        t.join()\n",
        "\n",
        "    print(f\"所有线程完成，最终计数器值: {counter}\")  # 预期 500000\n",
        "    print(f\"同步示例耗时: {time.time() - start_time:.2f}秒\\n\")\n",
        "\n",
        "def thread_communication_demo():\n",
        "    \"\"\"线程通信示例：使用 Event 实现通知机制\"\"\"\n",
        "    # 事件对象（用于线程间信号传递）\n",
        "    event = threading.Event()\n",
        "\n",
        "    def waiter():\n",
        "        print(\"等待线程: 等待通知...\")\n",
        "        event.wait()  # 阻塞等待事件触发\n",
        "        print(\"等待线程: 收到通知，开始工作\")\n",
        "        for i in range(3):\n",
        "            time.sleep(1)\n",
        "            print(f\"等待线程: 工作中 {i+1}/3\")\n",
        "        print(\"等待线程: 工作完成\")\n",
        "\n",
        "    def notifier():\n",
        "        print(\"通知线程: 准备工作...\")\n",
        "        time.sleep(2)  # 模拟准备时间\n",
        "        print(\"通知线程: 发送通知\")\n",
        "        event.set()  # 触发事件\n",
        "        time.sleep(1)\n",
        "        print(\"通知线程: 自身工作完成\")\n",
        "\n",
        "    # 创建并启动线程\n",
        "    t_wait = threading.Thread(target=waiter)\n",
        "    t_notify = threading.Thread(target=notifier)\n",
        "\n",
        "    t_wait.start()\n",
        "    t_notify.start()\n",
        "\n",
        "    t_wait.join()\n",
        "    t_notify.join()\n",
        "    print(\"线程通信示例结束\\n\")\n",
        "\n",
        "def thread_pool_demo():\n",
        "    \"\"\"线程池示例：使用 ThreadPoolExecutor 管理线程\"\"\"\n",
        "    def task(task_id):\n",
        "        sleep_time = random.uniform(0.5, 2.0)\n",
        "        time.sleep(sleep_time)\n",
        "        return f\"任务 {task_id} 完成，耗时 {sleep_time:.2f}秒\"\n",
        "\n",
        "    # 创建线程池（最大5个线程）\n",
        "    with ThreadPoolExecutor(max_workers=5) as executor:\n",
        "        # 提交10个任务\n",
        "        futures = [executor.submit(task, i) for i in range(10)]\n",
        "\n",
        "        # 获取任务结果\n",
        "        for future in futures:\n",
        "            print(future.result())  # 阻塞等待结果\n",
        "\n",
        "    print(\"线程池示例结束\")\n",
        "\n",
        "def main():\n",
        "    print(\"===== 基础线程示例 =====\")\n",
        "    basic_thread_demo()\n",
        "\n",
        "    print(\"===== 自定义线程示例 =====\")\n",
        "    custom_thread_demo()\n",
        "\n",
        "    print(\"===== 线程同步示例 =====\")\n",
        "    thread_synchronization_demo()\n",
        "\n",
        "    print(\"===== 线程通信示例 =====\")\n",
        "    thread_communication_demo()\n",
        "\n",
        "    print(\"===== 线程池示例 =====\")\n",
        "    thread_pool_demo()\n",
        "\n",
        "if __name__ == \"__main__\":\n",
        "    main()\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "0f0e78c1",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Python3 XML 解析\n",
        "import xml.etree.ElementTree as ET\n",
        "\n",
        "def elementtree_demo():\n",
        "    # 1. 解析XML文件\n",
        "    tree = ET.parse('books.xml')\n",
        "    root = tree.getroot()  # 获取根元素 <bookstore>\n",
        "\n",
        "    # 2. 遍历XML结构\n",
        "    print(\"===== 遍历所有书籍 =====\")\n",
        "    for book in root.findall('book'):  # 查找所有book子元素\n",
        "        # 获取属性\n",
        "        category = book.get('category')\n",
        "        # 获取子元素文本\n",
        "        title = book.find('title').text\n",
        "        lang = book.find('title').get('lang')\n",
        "        author = book.find('author').text\n",
        "        year = book.find('year').text\n",
        "        price = book.find('price').text\n",
        "        \n",
        "        print(f\"类别: {category}, 标题: {title} ({lang}), 作者: {author}, 年份: {year}, 价格: {price}\")\n",
        "\n",
        "    # 3. 按条件查询（XPath语法）\n",
        "    print(\"\\n===== 价格大于30的书籍 =====\")\n",
        "    # 使用XPath查找价格>30的book元素\n",
        "    expensive_books = root.findall(\".//book[price > 30]\")\n",
        "    for book in expensive_books:\n",
        "        print(f\"{book.find('title').text} - 价格: {book.find('price').text}\")\n",
        "\n",
        "    # 4. 修改XML内容\n",
        "    print(\"\\n===== 修改XML =====\")\n",
        "    # 找到第一本书并修改价格\n",
        "    first_book = root.find('book')\n",
        "    price_elem = first_book.find('price')\n",
        "    price_elem.text = '35.99'  # 修改文本\n",
        "    price_elem.set('updated', 'true')  # 添加属性\n",
        "\n",
        "    # 5. 添加新元素\n",
        "    new_book = ET.Element('book', {'category': 'science'})\n",
        "    ET.SubElement(new_book, 'title', {'lang': 'en'}).text = 'Python Science'\n",
        "    ET.SubElement(new_book, 'author').text = 'John Smith'\n",
        "    ET.SubElement(new_book, 'year').text = '2023'\n",
        "    ET.SubElement(new_book, 'price').text = '45.50'\n",
        "    root.append(new_book)  # 添加到根元素\n",
        "\n",
        "    # 6. 删除元素\n",
        "    # 删除年份为2003的书籍\n",
        "    for book in root.findall('book'):\n",
        "        if book.find('year').text == '2003':\n",
        "            root.remove(book)\n",
        "\n",
        "    # 7. 保存修改到新文件\n",
        "    tree.write('updated_books.xml', encoding='utf-8', xml_declaration=True)\n",
        "    print(\"修改后的XML已保存到 updated_books.xml\")\n",
        "\n",
        "if __name__ == \"__main__\":\n",
        "    elementtree_demo()\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "73e6274b",
      "metadata": {},
      "outputs": [],
      "source": [
        "# 定义输入文件路径（需根据你的实际文件位置修改，例如 \"C:/test/11.txt\"）\n",
        "input_file_path = \"11.txt\"\n",
        "# 定义输出文件路径（新文件保存位置，可自定义）\n",
        "output_file_path = \"processed_11.txt\"\n",
        "\n",
        "# 打开输入文件（只读模式）和输出文件（写入模式，若文件不存在则创建）\n",
        "with open(input_file_path, \"r\", encoding=\"utf-8\") as input_file, \\\n",
        "     open(output_file_path, \"w\", encoding=\"utf-8\") as output_file:\n",
        "    \n",
        "    # 逐行读取输入文件内容\n",
        "    for line in input_file:\n",
        "        # 关键步骤：删除每行前10个字符\n",
        "        # 若行长度不足10个字符，切片后会返回空字符串（避免报错）\n",
        "        processed_line = line[10:]\n",
        "        # 将处理后的行写入输出文件\n",
        "        output_file.write(processed_line)\n",
        "\n",
        "# 执行完成后提示\n",
        "print(f\"处理完成！结果已保存到：{output_file_path}\")"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "myenv",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.18"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}